package itsm.isperp.module.controller.api.wechat;

import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.service.app.AppUserService;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-3-15
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("api/wechat/userAccount")
public class WechatUserAccountController {

	@Autowired
	AppUserService appUserService;

	@RequestMapping("view")
	public ModelAndView view(String openid) {
		ModelAndView mv = new ModelAndView("api/wechat/userAccount/view");

		AppUser model = appUserService.findByOpenid(openid);
		if(model.isEnable()==false && model.getStatus().equals("待审核"))
		{
		  mv.addObject("status","待审核");
		}else
		{
		  mv.addObject("status","正常");
		}
		mv.addObject("model", model);
		mv.addObject("openid", openid);
		return mv;
	}
	
	@RequestMapping("infoEdit")
  public ModelAndView infoEdit(String fn,String cl,String ov,String openid) {
    ModelAndView mv = new ModelAndView("api/wechat/userAccount/infoEdit");
    AppUser model = appUserService.findByOpenid(openid);
    mv.addObject("fn", fn);
    mv.addObject("cl", cl);
    mv.addObject("ov", ov);
    mv.addObject("model", model);
    return mv;
  }
	
	 @RequestMapping("saveInfo")
	  public ModelAndView saveInfo(HttpServletRequest request,
	      RedirectAttributes redirectAttributes,String id,String cl) {
	    ModelAndView mv = new ModelAndView();
	    AppUser model = appUserService.findOne(id);
	    String value=request.getParameter(cl);
	    switch(cl)
	    {
	    case "fullname":
	      model.setFullname(value);
	      break;
	    case "email":
	      model.setEmail(value);
	      break;
	    case "address":
        model.setAddress(value);
        break;
	    case "mobile":
        model.setMobile(value);
        break;
	    case "birthDayDayAndMonth":
	      model.setBirthdayDay(request.getParameter("birthdayDay"));
	      model.setBirthdayMonth(request.getParameter("birthdayMonth"));
	      break;
	    }
	    appUserService.saveOrUpdate(model);
	    String openid=model.getOpenid();
	    redirectAttributes.addAttribute("openid", openid);
	    mv.setViewName("redirect:/api/wechat/userAccount/view");
	    return mv;
	  }

	@RequestMapping("deleteAccount")
	public ModelAndView deleteAccount(String id, String openid,
			HttpServletRequest request, RedirectAttributes redirectAttributes) {

		ModelAndView mv = new ModelAndView();
		appUserService.clearOpenid(id);
		redirectAttributes.addAttribute("openid", openid);
		mv.setViewName("redirect:/api/wechat/setting/register");

		return mv;
	}

}
